from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.generics import RetrieveAPIView
from rest_framework.views import APIView
from lhc_questions.serializers import LabelModelSerializer, QuestionModelSerializer, PubQuestionModelSerializer, \
    LabelsDetailInfoSerializer, LabelsSerializer, ReplySerializerForCreate, QuestionDetailSerializer
from xj_users.models import Question, Label, Reply

'''右上角更多显示标签'''
class Label_Full(APIView):


    def get(self, request):
        # 1.查询数据
        labels = Label.objects.all()
        # 2.创建序列化器，并传递查询结果集（设置many=True）
        serializer = LabelModelSerializer(labels, many=True)
        # 3.返回响应 serializer.data 就是字典列表
        return Response(serializer.data)


"""获取所有标签列表"""
class Articles_serch(APIView):


    def get(self,request):
        item=[]
        objects = Label.objects.all()
        for i in objects:
            item.append({'id':i.id,
                         'label_name':i.label_name})

        return Response(item)


'''用户关注的标签'''
class LabelsFollowView(APIView):
    def get(self, request):
        user = request.user
        labels = user.labels.all()
        serializer = LabelsSerializer(labels, many=True)
        return Response(serializer.data)


'''发布问题'''
class Questions(APIView):
    def post(self,request):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            request_data = request.data
            request_data["user"] = user.id
            s = PubQuestionModelSerializer(data=request_data)
            s.is_valid(raise_exception=True)
            s.save()
            return Response({'success': True, 'message': '发表成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


'''最新回答的问题'''
class QuestionsNew(APIView):

    def get(self, request, pk):
        '''查询labelid为pk的所有问题,按照回复的时间进行降序'''
        if pk == "-1":
            questions = Question.objects.all().order_by("-replytime")
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all().order_by("-replytime")
        serializer = QuestionModelSerializer(questions, many=True)
        return Response(serializer.data)


'''热门回答的问题'''
class QuestionsHot(APIView):
    def get(self,request,pk):
        '''查询labelid为pk的所有问题,按照回复的数量进行降序'''
        if pk == "-1":
            questions = Question.objects.all().order_by("-reply")
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all().order_by("-reply")
        serializer = QuestionModelSerializer(questions, many=True)
        return Response(serializer.data)


'''等待回答的问题'''
class QusetionsWait(APIView):
    def get(self, request, pk):
        '''查询labelid为pk未解答的问题,按照问题创建的时间降序'''
        if pk == "-1":
            questions = Question.objects.all()
        else:
            label = Label.objects.get(id=pk)
            questions = label.questions.all()
        questions = questions.filter(reply=0).order_by("-createtime")
        serializer = QuestionModelSerializer(questions, many=True)
        return Response(serializer.data)


'''问题详情页'''
class QuestionsDetils(APIView):

    def get(self,request,pk):
        # 根据传入问题ID获取问题
        question = Question.objects.get(pk=pk)

        # 访问量+1
        question.visits += 1
        question.save()

        # 根据回答表中问题外键获取问题
        questions = question.replies.all()
        question.comment_question = []
        question.answer_question = []

        for item in questions:
            if item.type == 0:  # 问题的评论
                question.comment_question.append(item)
            elif item.type == 2:  # 回答的评论
                question.answer_question.append(item)

        ser = QuestionDetailSerializer(question)
        return Response(ser.data)

'''问题有用'''
class QuestionUseful(APIView):

    def put(self, request, pk):

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('question')
            flag = redis_conn.hget("question_userful_%s" % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                question = Question.objects.get(id=pk)
                question.useful_count += 1
                question.save()
                redis_conn.hset("question_userful_%s" % user.id, pk, 1)
                return Response({'success': True, 'message': '更新成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)



'''问题没用'''
class QuestionUnuseful(APIView):

    def put(self, request, pk):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('question')
            flag = redis_conn.hget('question_unuserful_%s' % user.id, pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                question = Question.objects.get(id=pk)
                question.unuseful_count += 1
                question.save()
                redis_conn.hset('question_unuserful_%s' % user.id, pk, 1)
                return Response({'success': True, 'message': '更新成功'})

        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

'''回答问题'''
class ReplyQusetionView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None:

            # 接收参数
            request_data = request.data
            request_data["user"] = user.id
            s = ReplySerializerForCreate(data=request_data)
            s.is_valid(raise_exception=True)
            reply = s.save()
            problem = reply.problem
            # 如果是回答,则更新对应的数据
            if request_data.get('type') == 2:
                problem.reply += 1
                problem.replyname = reply.user.username
                problem.replytime = reply.createtime
                problem.save()
            return Response({'success': True, 'message': '发表成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


'''回答有用'''
class QuestionAnswerUseful(APIView):
    permission_classes = [IsAuthenticated]
    def put(self,request,pk):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None:

            redis_conn = get_redis_connection('reply')
            flag = redis_conn.hget('reply_userful_%s" % user.id', pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                reply = Reply.objects.get(id=pk)
                reply.useful_count += 1
                reply.save()
                redis_conn.hset('reply_userful_%s" % user.id', pk, 1)
                return Response({'success': True, 'message': '操作成功'})

        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


'''回答无用'''
class QuestionAnswerUnuseful(APIView):
    permission_classes = [IsAuthenticated]
    def put(self, request, pk):

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None:

            redis_conn = get_redis_connection('reply')
            flag = redis_conn.hget('reply_unuserful_%s" % user.id', pk)
            if flag:
                return Response({'success': False, 'message': '请不要重复操作'})
            else:
                reply = Reply.objects.get(id=pk)
                reply.unuseful_count += 1
                reply.save()
                redis_conn.hset('reply_unuserful_%s" % user.id', pk, 1)
                return Response({'success': True, 'message': '更新成功'})

        else:
            return Response({'success': False, 'message': '未登录'}, status=400)


'''关注标签'''
class UserFocusinLabel(APIView):
    permission_classes = [IsAuthenticated]
    def put(self,request,pk):
        user=request.user
        try:
            label=Label.objects.get(id=pk)
        except Label.DoesNotExist:
            return Response({'message': "查询数据库失败",
                                      'success': 'false'})
        label.users.add(user)
        label.save()
        return Response({'message': "关注成功",
                                      'success': 'true'})


'''取消关注标签'''
class UserFocusoutLabel(APIView):
    permission_classes = [IsAuthenticated]
    def put(self,request,pk):
        user=request.user
        try:
            label=Label.objects.get(id=pk)
        except Label.DoesNotExist:
            return Response({'message': "查询数据库失败",
                                      'success': 'false'})

        label.users.remove(user)
        label.save()
        return Response({"message":"取消关注成功","success":"true"})



'''标签详情'''
class LabelsDetail(RetrieveAPIView):
    serializer_class = LabelsDetailInfoSerializer
    queryset = Label.objects.all()